package com.ruoyi.mall.service.impl;

import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;

import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.enums.AttachmentEnum;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.PrimaryKeyIdUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.mall.api.domian.AttributeValue;
import com.ruoyi.mall.domain.ProductGroupVO;
import com.ruoyi.mall.api.domian.ProductTagBind;
import com.ruoyi.mall.mapper.AttributeValueMapper;
import com.ruoyi.mall.mapper.ProductTagBindMapper;
import com.ruoyi.system.api.RemoteAttachmentService;
import com.ruoyi.system.api.RemoteFileService;
import com.ruoyi.system.api.domain.Attachment;
import com.ruoyi.system.api.domain.AttachmentVO;
import com.ruoyi.system.api.domain.UploadPicture;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import com.ruoyi.mall.mapper.ProductMapper;
import com.ruoyi.mall.api.domian.Product;
import com.ruoyi.mall.service.IProductService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 商品Service业务层处理
 * 
 * @author luogongquan
 * @date 2024-09-25
 */
@Service
public class ProductServiceImpl implements IProductService 
{
    @Autowired
    private ProductMapper productMapper;
    
    @Autowired
    private RemoteAttachmentService remoteAttachmentService;


    @Autowired
    private RemoteFileService remoteFileService;

    @Autowired
    private AttributeValueMapper attributeValueMapper;
    @Autowired
    private ProductTagBindMapper productTagBindMapper;

    /**
     * 查询商品
     * 
     * @param id 商品主键
     * @return 商品
     */
    @Override
    public Product selectProductById(Long id)
    {
        Product product = productMapper.selectProductById(id);
        //获取标签信息
        List<ProductTagBind> binds = productTagBindMapper.selectProductTagBindByProductId(id);
        product.setProductTagBinds(binds);
        return product;
    }

    /**
     * 查询商品列表
     * 
     * @param product 商品
     * @return 商品
     */
    @Override
    @Transactional
    public List<Product> selectProductList(Product product)
    {
        List<Product> products = productMapper.selectProductList(product);
        if(!products.isEmpty()){
            List<Long> collect = products.stream().map(Product::getId).collect(Collectors.toList());
            List<ProductGroupVO> binds = productTagBindMapper.selectProductTagBindByProductIds(collect);
            if(!binds.isEmpty()){
                Map<Long, String> collect1 = binds.stream().collect(Collectors.toMap(ProductGroupVO::getProductId, ProductGroupVO::getDescribe));
                products.forEach(p -> p.setTagDescribe(collect1.get(p.getId())));
            }

        }
        return products;
    }

    private void addTagBind(Product product) {
        if(StringUtils.isNotEmpty(product.getSymptomTags())){
            List<ProductTagBind> collect = product.getSymptomTags().stream().map(tag -> {
                ProductTagBind bind = new ProductTagBind();
                bind.setId(PrimaryKeyIdUtils.getSysIdWorker().nextId());
                bind.setProductId(product.getId());
                bind.setTagId(tag);
                return bind;
            }).collect(Collectors.toList());
            productTagBindMapper.batchInsertProductTagBind(collect);
        }
    }

    /**
     * 新增商品
     * 
     * @param product 商品
     * @return 结果
     */
    @Override
    @Transactional
    public int insertProduct(Product product)
    {
        product.setId(PrimaryKeyIdUtils.getSysIdWorker().nextId());
        product.setCreateTime(DateUtils.getNowDate());
        int i = productMapper.insertProduct(product);
        addTagBind(product);
        return i;
    }

    /**
     * 修改商品
     * 
     * @param product 商品
     * @return 结果
     */
    @Override
    @Transactional
    public int updateProduct(Product product)
    {
        Product old = productMapper.selectProductById(product.getId());

        product.setUpdateTime(DateUtils.getNowDate());
        int i = productMapper.updateProduct2MainImage(product);
        if(old.getMainImage() != null&&!old.getMainImage().equals(product.getMainImage())){
            //删除旧的图片
            remoteFileService.delete(new String[]{old.getMainImage()});
        }
        //删除旧的标签绑定
        productTagBindMapper.deleteProductTagBindByProductId(product.getId());
        addTagBind(product);
        return i;
    }

    /**
     * 批量删除商品
     * 
     * @param ids 需要删除的商品主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteProductByIds(Long[] ids)
    {
        List<Product> products = productMapper.selectProductByIds(ids);
        int i1 = productMapper.deleteProductByIds(ids);
        //删除属性
        attributeValueMapper.deleteAttributeValueByProductId(ids);
        //删除标签
        productTagBindMapper.deleteProductTagBindByProductIds(ids);
        List<String> strings = new ArrayList<>();
        List<Long> objects = new ArrayList<>(products.size()*2);
        for (int i = 0; i < products.size(); i++) {
            if(StringUtils.isNotEmpty(products.get(i).getMainImage())){
                strings.add(products.get(i).getMainImage());
            }
            if(ObjectUtils.isNotEmpty(products.get(i).getOtherImage())){
                objects.add(products.get(i).getOtherImage());
            }
            if(ObjectUtils.isNotEmpty(products.get(i).getQualificationsImage())){
                objects.add(products.get(i).getQualificationsImage());
            }
        }
        if(StringUtils.isNotEmpty(strings)){
            R<Boolean> delete = remoteFileService.delete(strings.toArray(new String[0]));
            if(delete.getCode() != HttpStatus.OK.value()){
                throw new ServiceException("删除失败");
            }
        }

        R r = remoteAttachmentService.batchDeleteAttachment(objects, SecurityConstants.INNER);
        if(r.getCode() != HttpStatus.OK.value()){
            throw new ServiceException("删除失败");
        }

        return i1;
    }

    /**
     * 删除商品信息
     * 
     * @param id 商品主键
     * @return 结果
     */
    @Override
    public int deleteProductById(Long id)
    {
        return productMapper.deleteProductById(id);
    }

    @Override
    public String getPicByPicId(Long picId) {

        return "";
    }

    @Override
    @Transactional
    public Boolean uploadOtherPic(UploadPicture uploadPicture) {
        Product product = productMapper.selectProductById(uploadPicture.getProductId());

        // 处理其他图片
        processImages(uploadPicture.getOtherImages(), product.getOtherImage(),imageId->{
            Product update = new Product();
            update.setId(uploadPicture.getProductId());
            update.setOtherImage(imageId);
            productMapper.updateProduct(update);
        });
        // 处理资格图片
        processImages(uploadPicture.getQualificationsImages(), product.getQualificationsImage(),imageId->{
            Product update = new Product();
            update.setId(uploadPicture.getProductId());
            update.setQualificationsImage(imageId);
            productMapper.updateProduct(update);
        });
        return true;
    }

    @Override
    public List<Product> selectProductByTagCode(String param) {
        return productMapper.selectProductByTagCode(param);
    }

    @Override
    public Product selectProductDetailById(Long id) {
        Product product = selectProductById(id);
        if(product != null){
            //其他属性
            List<AttributeValue> attributeValues = attributeValueMapper.selectAttributeValueByProductId(id);
            product.setAttributeValueList(attributeValues);
            //获取主要图片
            if(!StringUtils.isNull(product.getOtherImage())){
                R<List<Attachment>> pictureByAssociatedId = remoteAttachmentService.getPictureByAssociatedId(product.getOtherImage(), SecurityConstants.INNER);
                product.setAttachmentList(pictureByAssociatedId.getData());
            }
        }
        return product;
    }

    @Override
    public int changeListingFlag(Long id, String listingFlag) {
        Product product = new Product();
        product.setId(id);
        product.setListingFlag(listingFlag);
        product.setUpdateTime(DateUtils.getNowDate());
        product.setUpdateBy(SecurityUtils.getUsername());
        return productMapper.updateProduct(product);
    }


    private void processImages(List<Attachment> images, Long existingImageId, Consumer<Long> updateImageInfo) {
        /*if (StringUtils.isEmpty(images)) {
            return; // 无需处理
        }*/
        boolean update = false;
        AttachmentVO vo = new AttachmentVO();
        Long imageId = Optional.ofNullable(existingImageId)
                .orElse(PrimaryKeyIdUtils.getSysIdWorker().nextId());

        if (existingImageId != null) {
            // 先删除旧的
            vo.setDeleteAssociatedId(existingImageId);
        }else {
            update=true;
        }
        if (StringUtils.isNotEmpty(images)) {
            for (Attachment image : images) {
                image.setId(PrimaryKeyIdUtils.getSysIdWorker().nextId());
                image.setType(AttachmentEnum.PICTURE.getCode());
                image.setAssociatedId(imageId);
            }
        }

        vo.setAttachments(images);
        remoteAttachmentService.batchAdd(vo, SecurityConstants.INNER);
        if(update){
            updateImageInfo.accept(imageId);
        }
    }
}
